#!/usr/bin/env python
#coding: utf-8
'''
Created on 2017年5月4日

@author: Administrator
'''
from django.core.cache import cache
from django.contrib.auth.models import User

def make_key(user_id):
    """
        构造用户缓存key
    """
    return "user_detail_%s" % user_id

def set(user_id):
    """
        设置缓存
    """
    #构造用户json
    value = make_user_json(user_id)
    #设置缓存
    cache.set(make_key(user_id), value)

def get(user_id):
    """
        获取缓存
    """
    #获取缓存
    value = cache.get(make_key(user_id))
    #判断缓存是否存在
    if not value:
        #构造用户json
        value = make_user_json(user_id)
        #设置缓存
        cache.set(make_key(user_id), value)
    return value

def delete(user_id):
    """
        删除缓存
    """
    cache.delete(make_key(user_id))
    
def make_user_json(user_id):
    """
        构造用户json
    """
    record = {}
    try:
        user = User.objects.get(id=user_id)
    except User.DoesNotExist:
        return record
    record = {
        "id":user.id,
        "user_name":user.username,
        "first_name":user.first_name,
        "email":user.email,
        "mobile":user.profile.mobile if user.profile else "",
        "is_active":user.is_active,
    }
    return record
